package com.xugongzhang.demo;

import com.sun.xml.internal.ws.util.CompletedFuture;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author X
 * @date 2022/6/28 21:01
 * 电商比价的案例
 */
public class CompletableFutureMallDemo {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<String> sql = getPrice(list, "MySQL");
        for (String s : sql) {
            System.out.println(s);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("1耗时-->" + (endTime-startTime));

        long startTime2 = System.currentTimeMillis();
        List<String> sql1 = getPriceByCompletableFuture(list, "MySQL");
        for (String s : sql1) {
            System.out.println(s);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("2耗时-->" + (endTime2-startTime2));
    }

    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("dang"),
            new NetMall("tao"),
            new NetMall("yue"),
            new NetMall("ha")
    );
    // 价格
    public static List<String> getPrice(List<NetMall> list, String productName) {
        return list
                .stream()
                .map(netMall -> String.format(productName + " in %s price is %.2f",
                        netMall.getNetMallName(),
                        netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }

    public static List<String> getPriceByCompletableFuture(List<NetMall> list, String productName) {
        return list.stream()
                .map(netMall -> CompletableFuture.supplyAsync(() -> String.format(productName + " in %s price is %.2f",
                        netMall.getNetMallName(),
                        netMall.calcPrice(productName))))
                .collect(Collectors.toList())
                .stream()
                .map(s -> s.join())
                .collect(Collectors.toList());
    }
}

class NetMall {
    @Getter
    private String netMallName;

    public NetMall(String netMallName) {
        this.netMallName = netMallName;
    }

    public double calcPrice(String netMallName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + netMallName.charAt(0);
    }
}
